package com.qq.weixin.mp.message.hxexp.service.impl;

import java.io.IOException;
import java.io.StringReader;

import javax.xml.bind.JAXBException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.hxexp.weixin.common.jaxb.JaxbMarshallerHelper;
import com.hxexp.weixin.common.jaxb.JaxbUnmarshallerHelper;
import com.qq.weixin.constant.MsgType;
import com.qq.weixin.mp.message.hxexp.model.receive.BaseMsgJaxb;
import com.qq.weixin.mp.message.hxexp.model.receive.SubscribeEventJaxb;
import com.qq.weixin.mp.message.hxexp.model.send.TextReplyJaxb;
import com.qq.weixin.mp.message.hxexp.service.SubscribeEventService;

/**
 * 订阅事件服务实现类
 * @author li.jiang
 *
 */
@Service
public final class SubscribeEventServiceImpl implements SubscribeEventService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SubscribeEventServiceImpl.class);
    @Value("${subscribe.msg}")
    private String subscribeMsg;
    /* (non-Javadoc)
     * @see com.hxexp.weixin.pubac.reply.service.SubscribeEventService#receiveAndReply(java.lang.String)
     */
    @Override
    public String receiveAndReply(String xmlMsg) throws JAXBException, IOException {
        SubscribeEventJaxb subscribeEvent = (SubscribeEventJaxb) JaxbUnmarshallerHelper.unmarshal(new StringReader(xmlMsg),
                new Class<?>[] { BaseMsgJaxb.class, SubscribeEventJaxb.class });
        LOGGER.debug("接收到的消息已转换成对象: {}", subscribeEvent.toString());

        TextReplyJaxb replyMsg = new TextReplyJaxb();
        replyMsg.setToUserName(subscribeEvent.getFromUserName());
        replyMsg.setFromUserName(subscribeEvent.getToUserName());
        replyMsg.setCreateTime(System.currentTimeMillis());
        replyMsg.setMsgType(MsgType.TEXT);
        replyMsg.setContent(subscribeMsg);

        return JaxbMarshallerHelper.marshalToString(replyMsg);
    }

}
